package com.caiyi.tips.core.config;

import com.caiyi.tips.core.VO.ResultVO;
import com.caiyi.tips.core.exception.BaseException;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.binding.BindingException;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/*
 * @author Cliff.ZhouYang
 * @date 2017/11/17 15:14
 */
@ControllerAdvice
@ConfigurationProperties(prefix = "spring.profiles")
@Slf4j
public class GlobalExceptionHandler {
    private String active;

    private boolean writeExceptionFlag;

    /**
     * 拦截自定义的基于BaseException的异常
     * @return
     */
    @ExceptionHandler(BaseException.class)
    @ResponseBody
    public ResultVO baseExceptionHandler(BaseException e, HttpServletResponse response) {
        log.error("拦截自定义异常", e);
        return e.getResult();
    }

    /**
     * 参数校验异常
     * @param e
     * @param response
     * @return
     */
    @ExceptionHandler(BindException.class)
    @ResponseBody
    public ResultVO bindExceptionHandler(BindException e, HttpServletResponse response) {
        log.warn("参数校验异常", e);
        String msg = e.getBindingResult().getFieldError().getDefaultMessage();
        return ResultVO.failMsg(msg);
    }
    @ExceptionHandler//处理所有异常
    @ResponseBody //在返回自定义相应类的情况下必须有，这是@ControllerAdvice注解的规定
    public ResultVO exceptionHandler(Exception e, HttpServletResponse response) {
        ResultVO vo = null;
        vo = ResultVO.fail();
        if (writeExceptionFlag) {
            vo.setData(e.toString());
        }
        return vo;
    }

    public String getActive() {
        return active;
    }

    public void setActive(String active) {
        log.info("\n********************************************************\n\nspring.profiles.active=" + active +
                "\n\n********************************************************");
        this.active = active;
        if (active != null) {
            if (Objects.equals(active, "dev") || Objects.equals(active, "test")) {
                writeExceptionFlag = true;
            }
        }
    }
}
